package cn.jn.lhm.netty.part08.chat.handler;

import cn.hutool.core.util.StrUtil;
import cn.jn.lhm.netty.part08.chat.message.GroupChatRequestMessage;
import cn.jn.lhm.netty.part08.chat.message.GroupChatResponseMessage;
import cn.jn.lhm.netty.part08.chat.session.GroupSessionFactory;
import cn.jn.lhm.netty.part08.chat.session.SessionFactory;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;

import java.util.Set;

/**
 * @author lhm 2753914576@qq.com
 * @time 2023/11/1 - 20:54
 **/
@Slf4j
@ChannelHandler.Sharable
public class ServerGroupChatHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        Set<String> members = GroupSessionFactory.getGroupSession().getMembers(msg.getGroupName());
        GroupChatResponseMessage response = new GroupChatResponseMessage(msg.getGroupName(), msg.getFrom(), msg.getContent());
        for (String member : members) {
            if (!StrUtil.equals(member, msg.getFrom())) {
                SessionFactory.getSession().getChannel(member).writeAndFlush(response);
            }
        }
    }
}
